﻿package com.projects.xenia;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


import com.projects.xenia.global_modules.MainGlobalModule;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

public class GPSLocationActivity extends Activity {

	private LocationManager MyGPSLocation;
	
	private TextView LongtitudeTextView;
	private TextView LattitudeTextView;
	private TextView TimeTextView;
	private TextView AccuracyTextView;
	                                                                                                                                                                                                                                                                                                                               

	private Double LocationLongtitude;
	private Double LocationLattitude;
	private Float LocationAccuracy;
	private Date LocationTime;
	
	private Context Cntx;
	
	private final int IDR_GPSSettingsTest = 3;
	
	private ImageView _backward;
	
	
	private CheckBox NetLocationCheck;
	private CheckBox GPSLocationCheck;
	private ProgressBar TimeOutProgressBar;
	
	private Timer t; 
	
	private String docid;
	private int type_xdoc;
	
	
	private int VisitsLocAccuracy;
	private int VisitsLocTimeOut;
	private boolean VisitLocRough;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
				
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
		
		setContentView(R.layout.location_form);		
		
		Cntx = this;
		
		Bundle DocExtra = getIntent().getExtras();
		if (DocExtra!=null){
			docid = DocExtra.getString("docid"); 
			type_xdoc = DocExtra.getInt("type_xdoc");
		}
		else {
			docid = UUID.randomUUID().toString().toUpperCase();
			type_xdoc = 0;
		}
		
		VisitsLocAccuracy = Integer.parseInt(MainGlobalModule.ConstantsCollection.get("VisitsLocAccuracy"));
		VisitsLocTimeOut = Integer.parseInt(MainGlobalModule.ConstantsCollection.get("VisitsLocTimeOut"));
		VisitLocRough = Boolean.parseBoolean(MainGlobalModule.ConstantsCollection.get("VisitsLocTimeOut")); 
		
		_backward = (ImageView)findViewById(R.id._backward);
		_backward.setOnClickListener(_backward_Click);
		
		NetLocationCheck = (CheckBox) findViewById(R.id.NetLocationCheck);
		NetLocationCheck.setChecked(false);
		
		GPSLocationCheck = (CheckBox) findViewById(R.id.GPSLocationCheck);
		GPSLocationCheck.setChecked(false);				
		
		TimeOutProgressBar = (ProgressBar)findViewById(R.id.TimeOutProgressBar);				
		
		LongtitudeTextView = (TextView)findViewById(R.id.Longtitude);
		LattitudeTextView = (TextView)findViewById(R.id.Lattitude);

		TimeTextView = (TextView)findViewById(R.id.LocationTime);
		AccuracyTextView = (TextView)findViewById(R.id.Location_Accuracy);
		
		LocationLongtitude = 0.0d; 
		LocationLattitude = 0.0d;
		LocationAccuracy = 0f;
		LocationTime = null;
		
		MyGPSLocation = (LocationManager)getSystemService(LOCATION_SERVICE);		
		MyGPSLocation.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lLocationListener);
		MyGPSLocation.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, lLocationListener);
		MyGPSLocation.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, lLocationListener);
		
		if (!MainGlobalModule.CheckGPSSettings(false)) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		}
		else {
			StartTimer ();	
		}
				
		
	}
	
	private void StartTimer () {
		
		TimeOutProgressBar.setProgress(0);
		TimeOutProgressBar.setMax(VisitsLocTimeOut);		
		t = new Timer();		
		t.schedule(new TimerTask() {
			@Override
			public void run() {
				if (!MainGlobalModule.CheckGPSSettings(true)) {					
					t.cancel();
					startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
				}
				else {
					TimeOutProgressBar.setProgress(TimeOutProgressBar.getProgress()+1);
					if (TimeOutProgressBar.getProgress()==TimeOutProgressBar.getMax()) {
						t.cancel();						
						if (VisitLocRough & LocationAccuracy>0) {
							SaveGps ();
						}
						else {
							finishActivity();	
						}
					}	
				}
			}
		}, 0, 1000);		
		
	}
	 
	private LocationListener lLocationListener = new LocationListener() {
		
	
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onLocationChanged(Location location) {
			
			LongtitudeTextView.setText(String.valueOf(location.getLongitude()));
			LattitudeTextView.setText(String.valueOf(location.getLatitude()));
			AccuracyTextView.setText(String.valueOf(location.getAccuracy()));
			
			String Provider = location.getProvider();

			
			if (Provider.equals(LocationManager.NETWORK_PROVIDER)) {
				NetLocationCheck.setChecked(true);
			}
			
			if (Provider.equals(LocationManager.GPS_PROVIDER)) {
				GPSLocationCheck.setChecked(true);		
			}
			
			final DateFormat formatter = new SimpleDateFormat("dd.MM.yy HH:mm:ss");
	    	final Date dumpDate = new Date(location.getTime());	
			TimeTextView.setText(formatter.format(dumpDate));
			
			LocationLongtitude = location.getLongitude();
			LocationLattitude = location.getLatitude();
			LocationAccuracy = location.getAccuracy();
			LocationTime = new Date (location.getTime());
			
			if ((LocationAccuracy > 0) & (LocationAccuracy < VisitsLocAccuracy)) {				
				SaveGps ();
			}
			
		}
	};
	
	private void SaveGps () {
		
		ContentValues InsertUpdateValues = new ContentValues ();
		
		InsertUpdateValues.put("id", docid);
		InsertUpdateValues.put("type_xdoc",type_xdoc);
		
		InsertUpdateValues.put("date_create", MainGlobalModule.DateToSqlString(Calendar.getInstance().getTime()));
		InsertUpdateValues.put("state", 1);
		InsertUpdateValues.put("user_id", MainGlobalModule.SettingsCollection.get("ManagerId"));				
		InsertUpdateValues.put("longtitude", LocationLongtitude);
		InsertUpdateValues.put("lattitude", LocationLattitude);
		InsertUpdateValues.put("accuracy", LocationAccuracy);
		InsertUpdateValues.put("locationTime", MainGlobalModule.DateToSqlString(LocationTime));
		
		MainGlobalModule.DBE.insert("xdoc_gpslog", null, InsertUpdateValues);	
	
		setResult(RESULT_OK, null);
		
		finishActivity();
		
	}
	
	private void finishActivity() {
		
		MyGPSLocation.removeUpdates(lLocationListener);
		finish ();
		
	}
	
	private View.OnClickListener _backward_Click = new View.OnClickListener() {		
		@Override
		public void onClick(View v) {
			finishActivity();
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
	
		switch (keyCode){
	
		case KeyEvent.KEYCODE_BACK:
			   
			return (false);
		
		}
	
		return super.onKeyDown(keyCode, event);		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
		 
		 switch(requestCode) { 
		    case IDR_GPSSettingsTest:		    	
		    	if (!MainGlobalModule.CheckGPSSettings(true)) {			
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		    	}
		    	else {
		    		StartTimer ();
		    	}
		    	break;		    
		 }		 
		    	
	};	
	
}